package com.sanji.sjmallmanager.http;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallmanager.activity.ActivityManager;
import com.sanji.sjmallmodule.login.LoginActivity;
import com.sanji.sjmallutils.WaitDialog;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONObject;

/**
 * Created by zsf on 16-12-8.
 */

public class NoHttpManager<T> implements OnResponseListener<T> {

    private NoHttpListener<T> mListener;
    private boolean isLoading;
    private Request<T> mRequest;
    private Dialog mWaitDialog;
    private Context mCtx;

    public NoHttpManager(Context context, Request<T> request, NoHttpListener<T> httpListener, boolean canCancle, boolean isLoading) {
        mListener = httpListener;
        this.isLoading = isLoading;
        this.mRequest = request;
        if (context != null) {
            mCtx = context;
            mWaitDialog = new WaitDialog(context);
            mWaitDialog.setCancelable(canCancle);
        }
    }

    @Override
    public void onStart(int what) {
        if (isLoading && mWaitDialog != null && !mWaitDialog.isShowing() && null != mCtx) {
            mWaitDialog.show();
        }

    }

    @Override
    public void onSucceed(int what, Response<T> response) {
        if (mListener != null) {
            try {
                String result = response.get().toString();
                if (result.substring(0).equals("{")){
                    JSONObject object = new JSONObject(response.get().toString());
                    String errorCode = object.optString("errorCode");
                    if (ConfigAPI.LOGIN_URL.hashCode() != what && "unPaided".equals(errorCode)) {
                        Intent intent = new Intent(mCtx, LoginActivity.class);
                        intent.putExtra("blackCode", 1);
                        mCtx.startActivity(intent);
                        ActivityManager.finishAllActivity();
                    }else {
                        mListener.onSuccessed(what, response);
                    }
                }else{
                    mListener.onSuccessed(what, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onFailed(int what, Response<T> response) {
        if (mListener != null) {
            mListener.onFailed(what, response);
        }
    }

    @Override
    public void onFinish(int what) {
        if (isLoading && mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
        }
    }
}
